package com.sgb.kjwl.viewmodel.self.packers;

import android.view.Gravity;
import android.view.View;

import androidx.core.content.ContextCompat;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.self.SelfTeamIntroduceEntity;
import com.sgb.kjwl.model.entity.self.SelfTeamOfferEntity;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.ServiceEntity;
import com.sgb.kjwl.repository.SelfRepertory;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfTeamOfferEditActivity;
import com.sgb.kjwl.view.widget.TeamMultiPopWindow;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 *
 * @author WYJ
 * @date 2020/8/12
 */
public class SelfTeamOfferEditModel extends BaseViewModel implements TeamMultiPopWindow.FilterResultClick, TeamMultiPopWindow.IItemClick {

    private SelfRepertory mRepertory;
    private SelfTeamOfferEditActivity mActivity;

    private TeamMultiPopWindow mPopWindow;

    private OptionsPickerView mOptions;
    private int mOptionPos;

    public SelfTeamOfferEditModel(SelfTeamOfferEditActivity mActivity, SelfRepertory mRepertory) {
        this.mRepertory = mRepertory;
        this.mActivity = mActivity;
    }


    public void getCategoryData(String cid, View view) {
        Call<BaseEntity<List<PickSelectEntity>>> call;
        if (mPopWindow == null) {
            DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
            call = NewAPIManager.getInstance().getTeamNewInterfaceAPI().getCategoryList();
        } else {
            call = NewAPIManager.getInstance().getTeamNewInterfaceAPI().getSecondCategory(cid);
        }
        call.enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    updateData(response.body().getData(), view);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    private void updateData(List<PickSelectEntity> data, View view) {
        if (data == null || data.size() == 0) {
            return;
        }
        if (mPopWindow == null) {
            //初始化筛选
            mPopWindow = new TeamMultiPopWindow(mActivity);
            mPopWindow.setFilterResultClick(this);
            mPopWindow.onItemClick(this);
        }
        switch (mPopWindow.getType()) {
            case TeamMultiPopWindow.TYPE_DEFAULT:
                mPopWindow.setData1(data);
                break;
            case TeamMultiPopWindow.TYPE_TWO:
                mPopWindow.setData2(data);
                break;
            case TeamMultiPopWindow.TYPE_THR:
                mPopWindow.setData3(data);
                break;
            case TeamMultiPopWindow.TYPE_FOU:
                mPopWindow.setData4(data);
                break;
            case TeamMultiPopWindow.TYPE_FIV:
                mPopWindow.setData5(data);
                break;
            case TeamMultiPopWindow.TYPE_SIX:
                mPopWindow.setData6(data);
                break;
            default:
                break;
        }
        if (view != null) {
            showPop(view);
        }
    }

    @Override
    public void result(PickSelectEntity... entity) {
        if (entity == null || entity.length == 0) {
            return;
        }
        mActivity.getEntity().setFirstCategoryName("");
        mActivity.getEntity().setFirstCategoryNo("");
        mActivity.getEntity().setSecondCategoryName("");
        mActivity.getEntity().setSecondCategoryNo("");
        mActivity.getEntity().setThirdCategoryName("");
        mActivity.getEntity().setThirdCategoryNo("");
        mActivity.getEntity().setFourCategoryName("");
        mActivity.getEntity().setFourCategoryNo("");
        mActivity.getEntity().setFifthCategoryName("");
        mActivity.getEntity().setFifthCategoryNo("");
        mActivity.getEntity().setSixthCategoryName("");
        mActivity.getEntity().setSixthCategoryNo("");
        int length = entity.length;
        for (int i = 0; i < length; i++) {
            switch (i) {
                case 0:
                    mActivity.getEntity().setFirstCategoryName(entity[i].getProjectscale());
                    mActivity.getEntity().setFirstCategoryNo(entity[i].getNo());
                    break;
                case 1:
                    mActivity.getEntity().setSecondCategoryName(entity[i].getProjectscale());
                    mActivity.getEntity().setSecondCategoryNo(entity[i].getNo());
                    break;
                case 2:
                    mActivity.getEntity().setThirdCategoryName(entity[i].getProjectscale());
                    mActivity.getEntity().setThirdCategoryNo(entity[i].getNo());
                    break;
                case 3:
                    mActivity.getEntity().setFourCategoryName(entity[i].getProjectscale());
                    mActivity.getEntity().setFourCategoryNo(entity[i].getNo());
                    break;
                case 4:
                    mActivity.getEntity().setFifthCategoryName(entity[i].getProjectscale());
                    mActivity.getEntity().setFifthCategoryNo(entity[i].getNo());
                    break;
                case 5:
                    mActivity.getEntity().setSixthCategoryName(entity[i].getProjectscale());
                    mActivity.getEntity().setSixthCategoryNo(entity[i].getNo());
                    break;
                default:
                    break;
            }
        }
        mActivity.showWorkType();
    }

    @Override
    public void itemClick(String no, int position, String name) {
        getCategoryData(no, null);
    }

    public void showPop(View view) {
        if (mPopWindow == null) {
            getCategoryData("", view);
        } else {
            if (!mPopWindow.isShowing()) {
                mPopWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        }
    }

    // 报价方案
    public void showSchemesPop(List<String> schemes) {
        if (mOptions == null) {
            mOptions = new OptionsPickerBuilder(mActivity, (options1, options2, options3, v) -> {
                mOptionPos = options1;
                mActivity.updateQuotationScheme(options1);
            }).setCancelColor(ContextCompat.getColor(mActivity, R.color.color_666666)).setTitleColor(ContextCompat.getColor(mActivity, R.color.color_969696)).build();
        }
        mOptions.setTitleText("选择咨询客服");
        mOptions.setPicker(schemes);
        mOptions.setSelectOptions(mOptionPos);
        mOptions.show();
    }

    public void addTeamPrice(SelfTeamOfferEntity entity) {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().addTeamPrice(entity).enqueue(new Callback<BaseEntity<Object>>() {
            @Override
            public void onResponse(Call<BaseEntity<Object>> call, Response<BaseEntity<Object>> response) {
                DialogHelper.dismissProgressDialog();
                BaseEntity<Object> body = response.body();
                if (body == null || body.getState() == null) {
                    MToast.showToast(mActivity, "发布失败！");
                    return;
                }
                if (body.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    mActivity.editEntitySuccess();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mActivity, "发布失败！");
            }
        });
    }

    public void detailTeamPrice(SelfTeamOfferEntity entity) {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().detailTeamPrice(entity.getNo()).enqueue(new ICallBack<BaseEntity<SelfTeamOfferEntity>>() {
            @Override
            public void onSuccess(BaseEntity<SelfTeamOfferEntity> data) {
                if (data.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    mActivity.updateOfferEntity(data.getData());
                } else {
                    mActivity.showEmpty();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<SelfTeamOfferEntity>> call, Throwable t) {
                super.onFailure(call, t);
                mActivity.showEmpty();
            }
        });
    }

    public void getAddressModel() {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if ("200".equals(response.body().getCode())) {
                    mActivity.showAddressPop(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    // ------------------------------------------所需工种 -----------------------------------------------

    public void getWorkType() {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().getWorkType(2).
                enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                        DialogHelper.dismissProgressDialog();
                        if (response.body() == null || response.body().getState() == null) {
                            return;
                        }
                        if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                            mActivity.showPickWorkTypePop(response.body().getData());
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                    }
                });
    }

    // ------------------------------------------客服 -----------------------------------------------

    private List<PickSelectEntity> mServiceList = new ArrayList<>();

    public void getCustomerData(boolean isShow) {
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getMachineAPI().getCustomerOrg()
                .enqueue(new Callback<BaseEntity<List<ServiceEntity>>>() {
                             @Override
                             public void onResponse(Call<BaseEntity<List<ServiceEntity>>> call, Response<BaseEntity<List<ServiceEntity>>> response) {
                                 DialogHelper.dismissProgressDialog();
                                 if (response.body() == null || response.body().getState() == null) {
                                     return;
                                 }
                                 if (response.body().getState().equals(AppConstant.REQEUST_SECCUESS)) {
                                     List<ServiceEntity> data = response.body().getData();
                                     if (data == null || data.size() == 0) {
                                         return;
                                     }
                                     mServiceList = new ArrayList<>();
                                     for (int i = 0; i < data.size(); i++) {
                                         PickSelectEntity pickSelectEntity = new PickSelectEntity();
                                         pickSelectEntity.setNo(data.get(i).getId());
                                         pickSelectEntity.setProjectscale(data.get(i).getName());
                                         mServiceList.add(pickSelectEntity);
                                     }
                                     if (isShow) {
                                         showCustomerPop();
                                     }
                                 }
                             }

                             @Override
                             public void onFailure(Call<BaseEntity<List<ServiceEntity>>> call, Throwable t) {
                                 DialogHelper.dismissProgressDialog();
                             }
                         }
                );
    }

    /**
     * 咨询客服
     */
    public void showCustomerPop() {
        if (mServiceList == null || mServiceList.size() == 0) {
            getCustomerData(true);
            return;
        }
        // 咨询客服
        OptionsPickerView<PickSelectEntity> mCustomerOptions = new OptionsPickerBuilder(mActivity, (options1, options2, options3, v) -> mActivity.updateCustomer(mServiceList.get(options1))).build();
        mCustomerOptions.setTitleText("选择咨询客服");
        mCustomerOptions.setPicker(mServiceList);
        mCustomerOptions.setSelectOptions(0);
        mCustomerOptions.show();
    }

    //获取经纬度信息
    public void getLocationLL(String no, String cityNo, String areaNo) {
        DialogHelper.showProgressDialog(mActivity, null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().getLocationLL(mRepertory.getAreaCode(), no, cityNo, areaNo).enqueue(new Callback<BaseEntity<MapLongAndLatEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<MapLongAndLatEntity>> call, Response<BaseEntity<MapLongAndLatEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    mActivity.updateAddress(response.body().getData());
                } else {
                    MToast.showToast(mActivity.getActivity(), response.message());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<MapLongAndLatEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mActivity.getActivity(), t.getMessage());
            }
        });

    }

    // -------------------------------------------工队简介-------------------------------------------

    public void getTeamIntroduce() {
        Map map = new HashMap();
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        if ("".equals(companyNo) || "0".equals(companyNo)) {
            map.put("companyNo", "");
            map.put("userNo", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, ""));
        } else {
            map.put("companyNo", companyNo);
            map.put("userNo", "");
        }
        DialogHelper.showProgressDialog(mActivity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getTeamIntroduce(map).enqueue(new Callback<BaseEntity<SelfTeamIntroduceEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<SelfTeamIntroduceEntity>> call, Response<BaseEntity<SelfTeamIntroduceEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    mActivity.updateIntroduce(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<SelfTeamIntroduceEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //选择工队列表信息
    public void getNameByComAndUserNo() {
        String companyNos = "";
        String userNos = "";
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        if ("".equals(companyNo) || "0".equals(companyNo)) {
            companyNos = "";
            userNos = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        } else {
            companyNos = companyNo;
            userNos = "";
        }
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().getNameByComAndUserNo(companyNos, userNos).enqueue(new ICallBack<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PickSelectEntity>> data) {
                if (data.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    mActivity.showTeamNamePop(data.getData());
                }
            }
        });
    }
}
